// shopPages/login/login.js
import {
  get_carte,
  get_carte_count,
  get_open_id,
  user_login,
  user_login_v4
} from "../../utils/api.js";

const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    redirect_url:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    var pages = getCurrentPages()
    var currentPage = pages[pages.length - 2]
    var url = currentPage.route
    var options = currentPage.options
    let urlWithArgs = `/${url}?`
    for (let key in options) {
      const value = options[key]
      urlWithArgs += `${key}=${value}&`
    }
    urlWithArgs = urlWithArgs.substring(0, urlWithArgs.length - 1)
    that.setData({
      redirect_url: urlWithArgs
    });
  },
  to_back:function(){
    wx.navigateBack({
      delta: 1  // 返回上一级页面
    })
  },

  bindGetUserInfo: function (e) {
    const that = this
    var urlWithArgs = that.data.redirect_url;
    let userInfo = e.detail.userInfo
    try {
      var params2 = {
        openid: app.globalData.userInfo.openid,
        username: userInfo.nickName,
        logo: userInfo.avatarUrl,
        sex: userInfo.gender,
        timestamp: new Date().getTime(),
      };
      params2.sign = app.getSign(params2)
      app.HttpPostSend(
        user_login_v4, params2,
        function (result_data) {
          if (result_data.msg != "success") {
            app.showTipMsg(result_data.msg);
          } else {
            let userInfo = {
              ...result_data.data
            }
            app.globalData.userInfo = userInfo
            wx.setStorage({
              key: 'userInfo',
              data: JSON.stringify(userInfo)
            })
            wx.setStorage({
              key: 'openid',
              data: userInfo.openid
            })
            app.globalData.authSettingUser = 1;
            var persontest = /\/person\/person/;
            var carteShowtest = /\/carteShow\/carteShow/;
            var shoptest = /\/shop\/shop/;
            var buyCartest = /\/buyCar\/buyCar/;
            console.log(urlWithArgs);
            if (!persontest.test(urlWithArgs) && !carteShowtest.test(urlWithArgs) && !shoptest.test(urlWithArgs) && !buyCartest.test(urlWithArgs)) {
              wx.redirectTo({
                url: urlWithArgs,
              })
            } else {
              wx.switchTab({
                url: urlWithArgs,
              })
            }
            
          }
        })
    } catch (error) {

    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

})